package top.letscode.adclicker.store;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import top.letscode.adclicker.util.FileUtils;

public class SimpleDataStore {
  // <componentName, <数据名, 数据值>
  private static ConcurrentMap<String, ConcurrentMap<String, Object>> DATA_STORE =
      new ConcurrentHashMap<String, ConcurrentMap<String, Object>>();

  public static boolean containsComponent(String componentName) {
    return DATA_STORE.containsKey(componentName);
  }

  public static Object get(String componentName, String key) {
    if (!DATA_STORE.containsKey(componentName)) {
      return null;
    }
    return DATA_STORE.get(componentName).get(key);
  }

  @SuppressWarnings("unchecked")
  public static List<String> getFileLines(String componentName, String key) {
    if (!DATA_STORE.containsKey(componentName)) {
      DATA_STORE.put(componentName, new ConcurrentHashMap<String, Object>());
    }
    if (!DATA_STORE.get(componentName).containsKey(key)) {
      try {
        DATA_STORE.get(componentName).put(key, FileUtils.readFileToLines(key));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return (List<String>) DATA_STORE.get(componentName).get(key);
  }

  public static void put(String componentName, String key, Object value) {
    Map<String, Object> componentData = DATA_STORE.get(componentName);
    if (null == componentData) {
      DATA_STORE.putIfAbsent(componentName, new ConcurrentHashMap<String, Object>());
      componentData = DATA_STORE.get(componentName);
    }
    componentData.put(key, value);
  }

  public static void remove(String componentName, String key) {
    if (!DATA_STORE.containsKey(componentName)) {
      return;
    }
    DATA_STORE.get(componentName).remove(key);
  }

  public static void remove(String componentName) {
    if (!DATA_STORE.containsKey(componentName)) {
      return;
    }

    DATA_STORE.remove(componentName);
  }

  public static void clear(String componentName) {
    if (!DATA_STORE.containsKey(componentName)) {
      return;
    }

    DATA_STORE.get(componentName).clear();
  }
}
